package com.lx.filter;

import com.lx.config.WxConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import weixin.popular.bean.user.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤用户请求
 * @author lixing
 * @date 2021/5/25 14:52
 */
@Slf4j
@WebFilter(filterName = "WxAuthFilter",urlPatterns = "/profile/*")
public class WxAuthFilter implements Filter {

    @Autowired
    private WxConfig wxConfig;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("拦截/profile/* :{}"+request.toString());
        //1.判断用户登录状态
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        User user = (User) req.getSession().getAttribute("user");
        if (null == user || null == user.getNickname()) {
            //未登录，跳转授权页面
            String uri = req.getRequestURI();
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wxConfig.getAppID() + "" +
                    "&redirect_uri=" + wxConfig.getAppDomain() + "/auth?uri=" + uri + "&response_type=code&scope=snsapi_userinfo&state=base#wechat_redirect";
            resp.sendRedirect(url);
        } else {
            log.info("user:{}", ToStringBuilder.reflectionToString(user));
            filterChain.doFilter(req, resp);
        }
    }
/**
 * 如果想通过静默授权方式获取用户信息，必须第一次调用snsapi_userinfo方式，经用户授权之后，以后再通过snsapi_base获取用户信息之后，就不需要用户授权了，否则则会报48001错误
 * 静默授权url
 * "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->appId . "&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_base&state=base#wechat_redirect";
 * 网页授权url
 * "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->appId . "&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=userinfo#wechat_redirect";
 */

}
